

#include "abstractTree.h"

using namespace awa;


static void setParserOption(DOMBuilder* parser, \
			    const ParserOptions& opts ) {
  std::vector<IndexParserOptions> 
    features(getParserSupportedFeatures());

  for(std::vector<IndexParserOptions>::const_iterator i = features.begin(); i != features.end(); i++)
    if( std::find(opts.begin(), opts.end(), *i) != opts.end() )
      if( parser->canSetFeature( MapToXercesParserOptions(*i), true) )
	parser->setFeature( MapToXercesParserOptions(*i), true );
      else
	{
	  std::string msg( "Option " );
	  msg += XtoStr( MapToXercesParserOptions(*i) ) + std::string(" Not Available" );
	  throw XercesException( DOMException::NOT_SUPPORTED_ERR, 
				 *StrtoX( msg.c_str() ),
				 __FILE__,
				 __LINE__ );
	}
    else
      parser->setFeature( MapToXercesParserOptions(*i), false );
}

ComputationFlow awa::readFromSrc( const char* const uri, const ParserOptions& opts ) {
  
  try {
    
    DOMBuilder* xercesXmlParser( xerces::getXmlParser() );
    
    xerces::XmlErrorHandler parserError;
    
    xercesXmlParser->setErrorHandler( &parserError );
    
    setParserOption( xercesXmlParser, opts );
    
    DOMDocument* xmlDoc = xercesXmlParser->parseURI( uri );
    
    if( parserError.getSeverity() != xerces::XmlErrorHandler::DOMError::DOM_SEVERITY_WARNING )
      throw XercesException( DOMException::NOT_SUPPORTED_ERR, 
				  *parserError.getMessage(),
				  __FILE__,
				  __LINE__ );
    // get rid of empty text nodes
    xmlDoc->getDocumentElement()->normalize(); 
    
    return ComputationFlow( copyDOM( xmlDoc->getDocumentElement(), SHOW_ALL ^ SHOW_COMMENT ) );
  
  }
  catch(std::exception& e) {
    LOG(LOGLEVEL(CRITICAL), e.what());
  }

}
